package com.miyuan.view.replenish;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import android.widget.Toast;

import com.miyuan.R;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import com.miyuan.bean.ResultBean;
import com.miyuan.bean.request.AddReplenishmentParam;
import com.miyuan.bean.respone.GoodsListBean;
import com.miyuan.bean.respone.MachineDetailsBean;
import com.miyuan.bean.respone.VendorInfoBean;
import com.miyuan.net.NetService;
import com.miyuan.net.RetrofitClient;
import com.miyuan.utils.SPUtils;
import com.miyuan.view.machine.MachineInfosFragment;
import com.miyuan.view.machine.ModifyDetialsFragment;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class ReplenishFinishFragment extends Fragment {
    private Unbinder unbinder;
    @BindView(R.id.replenish_text)
    TextView replenish_text;
    @BindView(R.id.submit_button)
    Button submit_button;
    @BindView(R.id.back_layout)
    LinearLayout back;

    @BindView(R.id.machine_code)
    TextView machineCode;
    @BindView(R.id.machine_location)
    TextView machineLocation;
    @BindView(R.id.control_code)
    TextView controlCode;
    @BindView(R.id.machine_manager)
    TextView machineManager;
    @BindView(R.id.phone_num)
    TextView phoneNum;
    @BindView(R.id.replenish_money)
    TextView replenishMoney;


    ModifyReplenishFragment modifyReplenishFragment;
    String v;
    VendorInfoBean vendorInfoBean;

    public static ReplenishFinishFragment newInstance(String s) {
        ReplenishFinishFragment replenishFinishFragment = new ReplenishFinishFragment();
        Bundle bundle = new Bundle();
        bundle.putString("QrResult", s);
        replenishFinishFragment.setArguments(bundle);
        return replenishFinishFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_replenish_finish, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        v = getArguments().getString("QrResult");
//        Uri uri = Uri.parse(v);
//        final String code = uri.getQueryParameter("D");
        String[] params = v.split("\\?");
        String path;
        if (params.length > 1) {
            path = params[1];
        } else {
            path = params[0];
        }
        String[] pairs = path.split("&");
        String code = null;
        if (pairs.length > 0) {
            String keyValue = pairs[0];
            String[] values = keyValue.split("=");
            if (values.length > 1) {
                code = values[1];
            } else {
                Toast.makeText(getActivity(), "二维码不是正确的格式", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), "二维码不是正确的格式", Toast.LENGTH_SHORT).show();
        }
        if (code != null) {
            replenish_text.setText("工控号" + code);
//            "H11140N10S"
            RetrofitClient.getInstance()
                    .create(NetService.class)
                    .getVendorInfo(code)
                    .enqueue(new Callback<ResultBean<VendorInfoBean>>() {

                        @Override
                        public void onResponse(Call<ResultBean<VendorInfoBean>> call, Response<ResultBean<VendorInfoBean>> response) {
                            ResultBean<VendorInfoBean> resultBean = response.body();
                            if (resultBean.getData() != null) {
                                vendorInfoBean = resultBean.getData();
                                machineCode.setText(vendorInfoBean.getNumber());
                                machineLocation.setText(vendorInfoBean.getPointName());
                                controlCode.setText(vendorInfoBean.getControlNumber());
                                phoneNum.setText(vendorInfoBean.getPhone());
                                replenishMoney.setText(vendorInfoBean.getShouldRetrieveMoney() + "元");
                                machineManager.setText(vendorInfoBean.getName());
                            } else {
                                Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultBean<VendorInfoBean>> call, Throwable t) {

                        }
                    });
        }
    }

    @OnClick(R.id.back_layout)
    void back() {
        getActivity().finish();
    }

    @OnClick(R.id.submit_button)
    void submit() {
        if (vendorInfoBean != null) {
            String userId = SPUtils.getInstance().getString("userId");
            RetrofitClient.getInstance()
                    .create(NetService.class)
                    .addReplenishment(new AddReplenishmentParam(
                            vendorInfoBean.getControlNumber(),
                            vendorInfoBean.getNumbers(),
                            Integer.parseInt(vendorInfoBean.getTotalAmount()),
                            userId,
                            vendorInfoBean.getVendorId()
                    ).toRequestBody())
                    .enqueue(new Callback<ResultBean>() {

                        @Override
                        public void onResponse(Call<ResultBean> call, Response<ResultBean> response) {
                            ResultBean resultBean = response.body();
                            if (resultBean.getCode() == 0) {
                                Toast.makeText(getActivity(), "补货完成", Toast.LENGTH_SHORT).show();
                                getActivity().finish();
                            } else {
                                Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResultBean> call, Throwable t) {

                        }
                    });
        }
    }

    @OnClick(R.id.submit_text_view)
    void update() {
        if (vendorInfoBean != null) {
//            FragmentManager fm = getFragmentManager();
//            FragmentTransaction transaction = fm.beginTransaction();
//            modifyReplenishFragment = ModifyReplenishFragment.newInstance(vendorInfoBean);
//            transaction.replace(R.id.root_fragment, modifyReplenishFragment);
//            transaction.addToBackStack("modifyReplenishFragment");
//            transaction.commit();
            FragmentManager fm = getFragmentManager();
            FragmentTransaction transaction = fm.beginTransaction();
            Bundle bundle = getArguments();
            MachineDetailsBean machineDetailsBean = new MachineDetailsBean();
            machineDetailsBean.setControlNumber(vendorInfoBean.getControlNumber());
            machineDetailsBean.setPointName(vendorInfoBean.getPointName());
            machineDetailsBean.setNumber(vendorInfoBean.getNumber());
            bundle.putSerializable("machineDetailsBean", machineDetailsBean);
            bundle.putString("vendorId", vendorInfoBean.getVendorId());
            ModifyDetialsFragment modifyDetialsFragment = ModifyDetialsFragment.newInstance(bundle);
            transaction.replace(R.id.root_fragment, modifyDetialsFragment);
            transaction.addToBackStack("modifyDetialsFragment");
            transaction.commit();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }
}
